package com.wc.算法提高课.D第四章_高级数据结构.平衡树.营业额统计2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeSet;

/**
 * @Author congge
 * @Date 2024/5/28 0:02
 * @description https://www.acwing.com/problem/content/267/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 32768, INF = (int) 1e6 + 10;
    static TreeSet<Integer> set = new TreeSet<>();
    static int[] a = new int[N];
    static int n;

    public static void main(String[] args) {
        n = sc.nextInt();
        for (int i = 1; i <= n; i++) a[i] = sc.nextInt();
        set.add(INF);
        set.add(-INF);
        long res = 0;
        for (int i = 1; i <= n; i++) {
            if (i == 1) res += a[i];
            else res += Math.min(a[i] - set.floor(a[i]), set.ceiling(a[i]) - a[i]);
            set.add(a[i]);
        }
        out.println(res);
        out.flush();
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
